﻿using Common.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace Wicresoft.EKA.NRemedy
{
    public static class NRemeyGlobal
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(NRemeyGlobal));
        public static string Directory = "C:\\NRemedySerializers.xml";
        public static void Start()
        {
            //判定文件是否存在。
            if (File.Exists(Directory))
            {
                ARLoginContextSerializers contexts;
                FileStream f = new FileStream(Directory, FileMode.Open);
                XmlSerializer newSr = new XmlSerializer(typeof(ARLoginContextSerializers));
                try
                {
                    contexts = (ARLoginContextSerializers)newSr.Deserialize(f);
                }
                catch (Exception e)
                {
                    logger.Error(e);
                    contexts = null;
                }
                f.Close();
                if (contexts != null)
                {
                    ARLoginContextPool.Instance.InitContextPoolFromSerializer(contexts);
                }
                File.Delete(Directory);
            }
        }

        public static void End()
        {
            //显示移出Logincontext 退出登录
            //文件存在先删除 
            try
            {
                if (File.Exists(Directory)) File.Delete(Directory);
                TextWriter tr = new StreamWriter(Directory);
                XmlSerializer newSr = new XmlSerializer(typeof(ARLoginContextSerializers));

                //TODO 如果生产环境为 Ture;
                newSr.Serialize(tr, ARLoginContextPool.Instance.GetLoginContextSerializer(true));
                tr.Close();
            }
            catch (Exception e)
            {
                logger.Error(e);
            }
        }
    }
}
